//
//  StatusTimeConvertTool.swift
//  CFZWeiBo
//
//  Created by Cedric Zheng on 30/11/2016.
//  Copyright © 2016 Cedric Zheng. All rights reserved.
//

import Foundation

let calendar = Calendar.current

extension Date {
    
    var toTimeCompareSting: String {
        dateFormatter.locale = locale
        
        let hourMinuteFormat    = " HH:mm"
        let monthDateFormat     = "MM-dd"
        let yearFormat          = "yyyy-"
        
        if calendar.isDateInToday(self) {
            //如果是今天
            let timeInterval = Double(Date().timeIntervalSince(self))
            if timeInterval < 1.min {
                return "刚刚"
            } else if timeInterval < 1.hour {
                return "\(Int(timeInterval / 1.min))分钟前"
            } else {
                return "\(Int(timeInterval / 1.hour))小时前"
            }
        } else if calendar.isDateInYesterday(self) {
            //如果是昨天 10: 10
            dateFormatter.dateFormat = "昨天" + hourMinuteFormat

            return dateFormatter.string(from: self)
        } else {
            //首先要取到今年是哪一年 2016
            //再取到当前的date是哪一年, 再做比较
            let thisYear = calendar.component(.year, from: Date())
            let selfYear = calendar.component(.year, from: self)
            //是今年
            if thisYear == selfYear {
                dateFormatter.dateFormat = monthDateFormat + hourMinuteFormat

                return dateFormatter.string(from: self)
            }
                //往年
            else {
                dateFormatter.dateFormat = yearFormat + monthDateFormat + hourMinuteFormat

                return dateFormatter.string(from: self)
            }
        }
    }
    
}

extension String {
    
    func convertToDate(withDateFormatString dateFormatStrig: String, locale: Locale = Locale(identifier: "en")) -> Date? {
        dateFormatter.locale        = locale
        dateFormatter.dateFormat    = dateFormatStrig
        
        guard let dateFromString = dateFormatter.date(from: self) else {
            return nil
        }
        
        return dateFromString
    }
    
    func statusTimeStringToTimeCampareString(withDateFormatString dateFormatStrig: String, locale: Locale) -> String {
        
        guard let dateFromString = convertToDate(withDateFormatString: dateFormatStrig, locale: locale) else {
            print("Time string converting has error, Date from String is nil.")
            return ""
        }
        
        return dateFromString.toTimeCompareSting
    }
    
}

